<template>
  <div>
    <a-modal
      :visible="visible"
      :title="current ? '编辑' : '新增'"
      okText="确认无误并提交"
      cancelText="取消"
      @ok="handleOk"
      @cancel="handleCancel"
      :destroyOnClose="true"
      :maskClosable="false"
    >
      <a-form :form="form" layout="horizontal" :label-col="{ span: 6 }" :wrapper-col="{ span: 12 }">
        <a-form-item label="角色名">
          <a-input
            v-decorator="[
              'name',
              {
                rules: [{ required: true, message: '请输入角色名' }],
                initialValue: current ? current.name : undefined
              }
            ]"
          />
        </a-form-item>
        <a-form-item label="角色描述">
          <a-input
            v-decorator="[
              'describe',
              {
                rules: [{ required: true, message: '请输入角色描述' }],
                initialValue: current ? current.describe : undefined
              }
            ]"
          />
        </a-form-item>
        <a-form-item label="状态">
          <a-switch
            v-decorator="[
              'status',
              {
                valuePropName: 'checked',
                initialValue: current ? current.status : true
              }
            ]"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
export default {
  name: 'AddModal',
  props: {
    visible: Boolean,
    current: Object
  },
  data () {
    return {
      form: null
    }
  },
  created () {
    this.form = this.$form.createForm(this, {
      onFieldsChange: (_, changedFields) => {
        console.log('onFieldsChange', changedFields)
      },
      onValuesChange: (_, values) => {
        console.log('onValuesChange', values)
      },
      mapPropsToFields: () => {
        if (this.current) {
          return {
            name: this.$form.createFormField({
              value: this.current.name
            }),
            describe: this.$form.createFormField({
              value: this.current.describe
            }),
            status: this.$form.createFormField({
              value: this.current.status
            })
          }
        }
        return {}
      }
    })
  },
  watch: {
    visible (val) {
      if (!val) {
        this.form.resetFields()
      }
    }
  },
  methods: {
    handleOk () {
      this.form.validateFields((err, values) => {
        if (!err) {
          if (this.current) {
            values.id = this.current.id
          }
          this.$emit('ok', values)
        }
      })
    },
    handleCancel () {
      this.$emit('cancel')
    }
  }
}
</script>
